

#include "tcp_socket.h"
#include <cstddef>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <fcntl.h>

TcpSocket::TcpSocket()
{
    m_socket_fd = 0;
}

TcpSocket::TcpSocket(int socket)
{
    m_socket_fd = socket;
    SetOpt();
    SetNonBlocking();
}

void TcpSocket::Open()
{
    m_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
}

void TcpSocket::SetOpt()
{
    int val = 1;
    setsockopt(m_socket_fd, SOL_SOCKET, TCP_NODELAY , &val, sizeof(val));
    setsockopt(m_socket_fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val));
    setsockopt(m_socket_fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val));
}

void TcpSocket::SetNonBlocking()
{
    int old_mode = fcntl(m_socket_fd, F_GETFL);
    fcntl(m_socket_fd, F_SETFL, O_NONBLOCK | old_mode);
}

void TcpSocket::CloseFd()
{
    if (m_socket_fd != -1)
    {
        close(m_socket_fd);
    }
    m_socket_fd = -1;
}


